mod util;
use clap::{Arg, ArgAction, Command};
use itertools::Itertools;
use std::fs;
use std::io::{Error, ErrorKind};
use std::path::Path;

use util::{build_route_content, build_vue_module, get_file_names, VueModule};

fn main() {
    let matches = Command::new("Gen Route")
        .version("1.0")
        .author("caozongying<zongying_cao@163.com>")
        .about("caozongying_cao<zongying_cao@163.com> is the author of gen route")
        .arg(
            Arg::new("views")
                .short('i')
                .long("views")
                .value_name("VIEW_PATH")
                .help("views的路径")
                .action(ArgAction::Set),
        )
        .arg(
            Arg::new("output")
                .short('o')
                .long("output")
                .value_name("OUTPUT_FILE")
                .help("route文件的输出路径")
                .action(ArgAction::Set),
        )
        .get_matches();

    let view_path = matches
        .get_one::<String>("views")
        .expect("views路径获取错误");
    let output_file = matches
        .get_one::<String>("output")
        .expect("output输出文件路径错误");

    if let Err(error) = get_file_names(Path::new(view_path))
        .and_then(|file_names| {
            file_names
                .into_iter()
                .map(|file_name| build_vue_module(&file_name))
                .try_collect()
                .map_err(|err| Error::new(ErrorKind::Other, err))
        })
        .map(|vue_modules| build_route_content(&vue_modules))
        .and_then(|content| fs::write(output_file, content))
    {
        println!("生成文件出错{}", error);
    } else {
        println!("生成文件成功");
    }
}
